public class GameOfLife {

    public void gameOfLife(int[][] board) {
        int m = board.length;
        int n = board[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int count = findNum(board, i, j, m, n, 1);
                if (board[i][j] == 1) {
                    if (count < 2 || count > 3) {
                        board[i][j] = 3;
                    }
                } else {
                    if (count == 3) board[i][j] = 2;
                }
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 2) board[i][j] = 1;
                if (board[i][j] == 3) board[i][j] = 0;
            }
        }
    }

    public int process(int[][] board, int i, int j, int m, int n, int target) {
        if (i < 0 || i >= m || j < 0 || j >= n) return 0;
        return board[i][j] == target || board[i][j] == target + 2 ? 1 : 0;
    }

    public int findNum(int[][] board, int i, int j, int m, int n, int target) {
        int count = 0;
        count += process(board, i + 1, j, m, n, target);
        count += process(board, i + 1, j + 1, m, n, target);
        count += process(board, i + 1, j - 1, m, n, target);
        count += process(board, i - 1, j, m, n, target);
        count += process(board, i - 1, j + 1, m, n, target);
        count += process(board, i - 1, j - 1, m, n, target);
        count += process(board, i, j + 1, m, n, target);
        count += process(board, i, j - 1, m, n, target);
        return count;
    }
}
